export const openWindow = (url, opts) => {
  const { target = '_blank', ...others } = opts || {};
  window.open(
    url,
    target,
    Object.entries(others)
      .reduce((preValue, curValue) => {
        const [key, value] = curValue;
        return [...preValue, `${key}=${value}`];
      }, [])
      .join(',')
  );
};

export const regexUrl = new RegExp(
  '^(?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$',
  'i'
);

export function workAreaHeight(height = 160) {
  const workAreaHeight = document.querySelector('.work-area').offsetHeight;
  return workAreaHeight - height;
}

/**
 * 获取屏幕高度
 * @param {number} height 要减去的高度
 * @return {number}
 */
export function screenHeight(height = 285) {
  const defaultHeight = 880;
  const clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
  console.log(clientHeight)
  if (clientHeight) {
    return clientHeight - height;
  }
  return defaultHeight - height;
}

/**
 * 文件下载
 */
export function downloadFile(url, filename = '') {
  // const blob = new Blob([data], {type: 'application/octet-stream'}); // 转换成二进制对象
  // const url = window.URL.createObjectURL(blob); // 二进制对象转换成url地址
  const linkElm = document.createElement('a');
  linkElm.setAttribute('download', '');
  linkElm.style.display = 'none';
  linkElm.href = url;
  // 对下载的文件命名
  const defaultFilename = url.split('/').pop().split('?')[0].split('#')[0]; // 从 URL 提取文件名
  linkElm.download = filename || defaultFilename;
  document.body.appendChild(linkElm);
  linkElm.click();
  // linkElm.remove();
  document.body.removeChild(linkElm); // 下载完成移除元素
  // window.URL.revokeObjectURL(url); // 释放掉blob对象
}

/**
 * API下载文件【支持批量下载】
 */
export function apiDownloadFile(url) {
  if (import.meta.env.VITE_API_BASE_URL) {
    const baseURL = import.meta.env.VITE_API_BASE_URL;

    // 支持批量下载
    const iframeElm = document.createElement('iframe');
    iframeElm.style.display = 'none';  // 防止影响页面
    iframeElm.style.height = '0';  // 防止影响页面
    iframeElm.src = `${baseURL}/adminapi/common/download?file=${url}`;
    document.body.appendChild(iframeElm);
    setTimeout(() => {
      iframeElm.remove();
    }, 5 * 60 * 1000);
  }
}

/**
 * 树状结构添加disabled
 */
export function disabledTree(tree, id, parentId = 0, disabledData = []) {
  tree.forEach(function (item, index) {
    if (item.id === id) {
      // 顶级
      item.disabled = true;
      disabledData[item.id] = true;
    } else if (item.parent_id === id && id !== parentId) {
      // 非顶级
      item.disabled = true;
      disabledData[item.parent_id] = true;
    } else if (item.parent_id !== 0 && item.parent_id === parentId && disabledData[item.parent_id]) {
      // 子集
      item.disabled = true;
      disabledData[item.id] = true;
    } else {
      //
    }
    if (item.children) {
      disabledTree(item.children, id, item.id, disabledData);
    }
  });
  return tree;
}

/**
 * 树状结构转为一维数组
 */
export function treeToList(tree, children = 'children') {
  let list = [];
  tree.forEach((item) => {
    list.push(item);
    if (item[children] && item[children].length > 0) {
      // list = [...list, ...treeToList(item[children])];
      list = [...list, ...item[children]];
    }
  });
  return list;
}

/**
 * 获取文件类型
 */
export function getFileType(src) {
  if (src) {
    const point = src.lastIndexOf('.');
    return src.substr(point + 1);
  }
  return '';
}

/**
 * 计算两个日期之间的差值
 */
export function getDiffDay(beginDate, endDate) {
  // 将两个日期都转换为毫秒格式，然后做差
  const beginTime = Date.parse(beginDate);
  const endTime = Date.parse(endDate);
  if (endTime > beginTime) {
    const diffDate = Math.abs(endTime - beginTime); // 取相差毫秒数的绝对值
    // return Math.floor(diffDate / (1000 * 3600 * 24)); // 向下取整
    return Math.ceil(diffDate / (1000 * 3600 * 24)); // 向上取整
  }
  return 0;
}

export function isEmptyObject(obj) {
  return Object.keys(obj).length === 0;
}

export function isNotEmptyObject(obj) {
  if (typeof obj === 'object') {
    if (Object.keys(obj).length > 0) {
      return true;
    }
  }
  return false;
}

/**
 * 生成随机字符串
 */
export function randomString(len) {
  const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  const maxPos = charset.length;
  let str = '';
  for (let i = 0; i < len; i ++) {
    str += charset.charAt(Math.floor(Math.random() * maxPos));
  }

  return str;
}

/**
 * 生成唯一标识ID
 */
export function generateId() {
  // toString(36) 将随机数转换为 36 进制的字符串
  // return Math.random().toString(36).substr(3, 10); // n3sr1qcff
  // return Number(Math.random().toString().substr(2, randomLength) + Date.now()).toString(36); // erj3vz0thkw0000
  // const timeStamp = Date.now().toString();
  const timeStamp = new Date().getTime();
  // const randomNum = Math.floor(Math.random() * 1000 * 1000).toString();
  const randomNum = (Math.random() * 1000 * 1000).toFixed(0);

  return `${timeStamp}${randomNum}`;
}
